package org.jeecg.modules.basic.material.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfo;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfoVO;
import org.jeecg.modules.basic.material.mapper.WmsBasicMaterialStockInfoMapper;
import org.jeecg.modules.basic.material.service.IWmsBasicMaterialStockInfoService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 物料绑定仓库设置信息
 * @Author: jeecg-boot
 * @Date:   2023-11-24
 * @Version: V1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WmsBasicMaterialStockInfoServiceImpl extends ServiceImpl<WmsBasicMaterialStockInfoMapper, WmsBasicMaterialStockInfo> implements IWmsBasicMaterialStockInfoService {

    @Override
    public void saveByCheck(WmsBasicMaterialStockInfo wmsBasicMaterialStockInfo) {
        WmsBasicMaterialStockInfo repe = this.getById(wmsBasicMaterialStockInfo.getId());
        if (ObjectUtil.isNotEmpty(repe)) {
            this.updateById(wmsBasicMaterialStockInfo);
        }else {
            //一个物料下同一仓库库区只能设置一条记录
            List<WmsBasicMaterialStockInfo> checkList = this.list(new LambdaQueryWrapper<WmsBasicMaterialStockInfo>().eq(WmsBasicMaterialStockInfo::getWmsBasicMaterialId, wmsBasicMaterialStockInfo.getWmsBasicMaterialId()));
            if (ObjectUtil.isNotEmpty(checkList)) {
                checkList.forEach(check -> {
                    if (wmsBasicMaterialStockInfo.getWarehouseId().equals(check.getWarehouseId()) && wmsBasicMaterialStockInfo.getWarehouseAreaId().equals(check.getWarehouseAreaId())) {
                        throw new JeecgBootException("物料库存信息存在重复设置!");
                    }
                });
            }
            this.save(wmsBasicMaterialStockInfo);
        }
    }

    @Override
    public void saveDataByCheck(WmsBasicMaterialStockInfoVO vo) {
        List<WmsBasicMaterialStockInfo> checkList = this.list(new LambdaQueryWrapper<WmsBasicMaterialStockInfo>().eq(WmsBasicMaterialStockInfo::getWmsBasicMaterialId, vo.getMaterialId()));
            this.removeBatchByIds(checkList);
            vo.getList().forEach(a -> {
                a.setId(null);
                this.save(a);
            });
    }
}
